<template>
  <div>
    <a-card v-if="searchData.studentId">
      <div ref="barChartIS" :style="{width:'100%',height:'368px'}"></div>
      <div ref="barChartOS" :style="{width:'100%',height:'368px'}"></div>
      <div ref="barChartPS" :style="{width:'100%',height:'368px'}"></div>
    </a-card>
    <a-card v-else>
      <div ref="barChartI" :style="{width:'100%',height:'368px'}"></div>
      <div ref="barChartO" :style="{width:'100%',height:'368px'}"></div>
      <div ref="barChartP" :style="{width:'100%',height:'368px'}"></div>
    </a-card>
  </div>
</template>
<script>

import { getAction } from '@/api/manage'
export default
{
  name: 'life',
  data() {
    return {
      url: {
        list: 'management/skArea/getAreaDuration',
        stuList: 'management/skArea/getStudentFavoriteArea'
      },
      searchData: {
        dateType: '',
        semesterId: '',
        classId: '',
        studentId: '',
        startDate: '',
        endDate: ''
      },
      color:["#0CDF8A","#3EACE5"],
      detailData: {},
      numList:[]
    }
  },
  props:["dataForm","monthName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    load() {
      const dataForm = this.dataForm
      this.numList = []
      console.log('dataForm', this.dataForm);
      // 查询列表数据
      this.searchData.dateType = dataForm.dateType;
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId;
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined;
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      this.searchData.startDate = dataForm.startDate;
      this.searchData.endDate = dataForm.endDate;
      if(dataForm.studentId) {
        this.studentChart()
      }else if(dataForm.classId) {
        this.classChart();
      }else{
        this.allChart();
      }
    },
    allChart() {
      let params = {
        areaType: '0', //0室内，1室外，2专业活动区
        timeScope: this.searchData.semesterId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }

      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数
          const classList = this.dataForm.classList.filter(item => { return item.id != ''});
          classList.forEach(el => {
            const classData = res.result.find(item => item.classId == el.id)
            if(classData){
              categorys.push(classData.className + classData.areaName);
              xData[0].push(classData.duration)
              xData[1].push(classData.studentTime)
              xData[2].push(classData.studentCount)
            } else {
              categorys.push(el.className);
              xData[0].push(0)
              xData[1].push(0)
              xData[2].push(0)
            }
          })
          this.initBarChart(this.$refs.barChartI, '室内受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })

      let params1 = {
        areaType: '1',
        timeScope: this.searchData.semesterId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params1).then((res)=>{
        if(res.success){
          var categorys = [];
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数

          res.result.forEach(item => {
            categorys.push(item.areaName);
            xData[0].push(item.duration)
            xData[1].push(item.studentTime)
            xData[2].push(item.studentCount)
          })
          this.initBarChart(this.$refs.barChartO, '室外受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })

      let params2 = {
        areaType: '2',
        timeScope: this.searchData.semesterId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params2).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数
          res.result.forEach(item => {
            categorys.push(item.areaName);
            xData[0].push(item.duration)
            xData[1].push(item.studentTime)
            xData[2].push(item.studentCount)
          })
          this.initBarChart(this.$refs.barChartP, '专业活动区受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    classChart() {
      const classInfo = this.dataForm.classList.find(item => item.id == this.searchData.classId)
      let params = {
        areaType: '0',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数
          if(res.result.length > 0){
            res.result.forEach(item => {
              categorys.push(item.areaName);
              xData[0].push(item.duration)
              xData[1].push(item.studentTime)
              xData[2].push(item.studentCount)
            })
          }else{
            categorys.push(classInfo.className);
            xData[0].push(0)
            xData[1].push(0)
            xData[2].push(0)
          }
          this.initBarChart(this.$refs.barChartI, '室内受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })

      let params1 = {
        areaType: '1',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params1).then((res)=>{
        if(res.success){
          var categorys = [];
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数
          res.result.forEach(item => {
            categorys.push(item.areaName);
            xData[0].push(item.duration)
            xData[1].push(item.studentTime)
            xData[2].push(item.studentCount)
          })
          this.initBarChart(this.$refs.barChartO, '室外受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })

      let params2 = {
        areaType: '2',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params2).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[],[]];//时长，人次，次数
          res.result.forEach(item => {
            categorys.push(item.areaName);
            xData[0].push(item.duration)
            xData[1].push(item.studentTime)
            xData[2].push(item.studentCount)
          })
          this.initBarChart(this.$refs.barChartP, '专业活动区受欢迎区域统计', categorys, xData);

        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    studentChart() {
      let params0 = {
        areaType: '0',//0室内，1室外，2专业活动区
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      // 室内
      getAction(this.url.stuList, params0).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[]];//时长

          // 每天
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));
            const dayDatas = res.result.filter(item => {
              return item.statisticalDate == rowString
            }).slice(0,2)
            if(dayDatas){
              xData[0].push(dayDatas.length>=1 ? {value: dayDatas[0].duration, top1: dayDatas[0].areaName} : {value: 0, top1: ''})
              xData[1].push(dayDatas.length>=2 ? {value: dayDatas[1].duration, top1: dayDatas[1].areaName} : {value: 0, top1: ''})
            } else {
              xData[0].push(0);
              xData[1].push(0);
            }
          }
          this.initBar2Chart(this.$refs.barChartIS, '喜爱室内区域统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })

      let params1 = {
        areaType: '1',//0室内，1室外，2专业活动区
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      // 室内
      getAction(this.url.stuList, params1).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[]];//时长

          // 每天
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));
            const dayDatas = res.result.filter(item => {
              return item.statisticalDate == rowString
            }).slice(0,2)
            if(dayDatas){
              xData[0].push(dayDatas.length>=1 ? {value: dayDatas[0].duration, top1: dayDatas[0].areaName} : {value: 0, top1: ''})
              xData[1].push(dayDatas.length>=2 ? {value: dayDatas[1].duration, top1: dayDatas[1].areaName} : {value: 0, top1: ''})
            } else {
              xData[0].push(0);
              xData[1].push(0);
            }
          }
          this.initBar2Chart(this.$refs.barChartOS, '喜爱室外区域统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
      let params2 = {
        areaType: '2',//0室内，1室外，2专业活动区
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      // 室内
      getAction(this.url.stuList, params2).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [[],[]];//时长

          // 每天
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));
            const dayDatas = res.result.filter(item => {
              return item.statisticalDate == rowString
            }).slice(0,2)
            if(dayDatas){
              xData[0].push(dayDatas.length>=1 ? {value: dayDatas[0].duration, top1: dayDatas[0].areaName} : {value: 0, top1: ''})
              xData[1].push(dayDatas.length>=2 ? {value: dayDatas[1].duration, top1: dayDatas[1].areaName} : {value: 0, top1: ''})
            } else {
              xData[0].push(0);
              xData[1].push(0);
            }
          }
          this.initBar2Chart(this.$refs.barChartPS, '喜爱专业活动区域统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    initBarChart(el, title, categorys, xData) {
      this.$forceUpdate()
      var myChartSports
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      const legendTitle = ['时长(分钟)','人次','人数'];
      let optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          right: '20%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: [
          {
            type: 'value',
            name: legendTitle[0],
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#999"
              }
            },
          },
          {
            type: 'value',
            name: legendTitle[1],
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#999"
              }
            },
            axisLabel: {
              formatter: '{value}'
            },
          },
          {
            type: 'value',
            name: legendTitle[2],
            position: 'right',
            offset: 80, // y轴位置的偏移量
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#999"
              }
            },
            axisLabel: {
              formatter: '{value}'
            },
          }
        ],
        series: [
          {
            name: legendTitle[0],
            data: xData[0],
            type: 'line',
            // barWidth: 10,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                // barBorderRadius: [5,5,0,0],
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            }
          },
          {
            name: legendTitle[1],
            data: xData[1],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: '#91cc75',
                label : {
                  show: true // 显示数据
                },
              }
            }
          },
          {
            name: legendTitle[2],
            data: xData[2],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 2,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: '#FFC005',
                label : {
                  show: true // 显示数据
                },
              }
            }
          }
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initBar2Chart(el, title, categorys, xData) {
      this.$forceUpdate()
      var myChartSports
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      const legendTitle = ['室内活动区Top1', '室内活动区Top2'];
      let optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          },
          formatter: function (params) {
            let tooltipStr = ``;
            if(params[0].data.top1 != ''){
              tooltipStr +=  `${params[0].marker} ${params[0].seriesName}&nbsp;&nbsp;&nbsp;${params[0].data.top1}`;
            }
            if(params[1].data.top1 != ''){
              tooltipStr +=  `<br />${params[1].marker} ${params[1].seriesName}&nbsp;&nbsp;&nbsp;${params[1].data.top1}`;
            }
            return tooltipStr;
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          right: '10%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: [
          {
            type: 'value',
            name: '时长(分钟)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#999"
              }
            },
          },
        ],
        series: [
          {
            name: legendTitle[0],
            data: xData[0],
            type: 'bar',
            barWidth: 10,
            stack: '时长(分钟)',
            itemStyle: {
              normal: {
                // barBorderRadius: [5,5,0,0],
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            }
          },
          {
            name: legendTitle[1],
            data: xData[1],
            type: 'bar',
            barWidth: 10,
            stack: '时长(分钟)',
            itemStyle: {
              normal: {
                // barBorderRadius: [5,5,0,0],
                color: '#91cc75',
                label : {
                  show: true // 显示数据
                },
              }
            }
          },
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if (this.numList.length == 3) {
        this.$emit("ok")
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>